import React, { forwardRef, useState ,useEffect} from 'react'
import {Form,Input,Select } from 'antd'
import { EyeInvisibleOutlined, EyeTwoTone } from '@ant-design/icons';
const {Option}=Select
// forwardRef是ref中的一个方法，他会在函数中放两个形参，一个item,ref,ref的值是从他的父组件中传过来的，所以还需要在父组件中创建ref，和传值
// 
const UserForm=forwardRef((props:any,ref)=>{
  const {regionList,roleList}=props;
  const [isDisabled,setisDisabled]=useState(false)
  useEffect(()=>{
    setisDisabled(props.isUpdateDisabled)
  },[props.isUpdateDisabled])
//   console.log(ref);
const {roleId,region}=JSON.parse(localStorage.getItem('token'))
const roleObj={
  "1":"superAdmin",
  "2":'admin',
  "3":"editor"
}
// console.log(props.isUpdate);
// console.log(list);
// 是否禁用区域
const checkRegionDisabled=(item)=>{
  // console.log(item);
  if(props.isUpdate ){
    // 更新用户
    if(roleObj[roleId]==='superAdmin'){
        return false
    }else{
      return true
    }
      }else{
    // 添加用户
      if(roleObj[roleId]==='superAdmin'){
        return false
    }else{
      // 亚洲!==亚洲false表示没被禁用，表示相同才不会被禁用
      return item.value!==region
    }
  }
}
// 是否禁用角色
const checkRoleIdDisabled=(item)=>{
  if(props.isUpdate ){
    // 更新用户
    if(roleObj[roleId]==='superAdmin'){
        return false
    }else{
      return true
    }
     }else{
    // 添加用户
      if(roleObj[roleId]==='superAdmin'){
        return false
    }else{
      // 只有区域编辑可选
      return roleObj[item.id]!=="editor"
    }
  }
}
  return (
    <Form layout='vertical' ref={ref}>
      <Form.Item
        name="username"
        label="用户名"
        rules={[{ required: true, message: '请输入正确的用户名!' }]}
      >
      <Input />
      </Form.Item>
      <Form.Item
        name="password"
        label="密码"
        rules={[{ required: true, message: '请输入正确的密码!' }]}
      >
         <Input.Password
        iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
      />
      </Form.Item>
      <Form.Item
        name="region"
        label="区域"
        rules={isDisabled?[]:[{ required: true, message: 'Please input your username!' }]}
      >
     <Select disabled={isDisabled}>
     {
      regionList.map(item=>{
        return(<Option value={item.value} key={item.id} disabled={checkRegionDisabled(item)}>{item.title}</Option>)
      })
     }
     </Select>
      </Form.Item>
      <Form.Item
        name="roleId"
        label="角色"
        rules={[{ required: true, message: 'Please input your username!' }]}
      >
      <Select onChange={(value)=>{
       if(value===1){
        setisDisabled(true)
        // 设置表单元素内部的值
        ref.current.setFieldsValue({
          region:""
      })
       }else{
         setisDisabled(false)
       }
      }}>
     {
      roleList.map(item=>{
        return(<Option value={item.id} key={item.id} disabled={checkRoleIdDisabled(item)}>{item.roleName}</Option>)
      })
     }
     </Select>
      </Form.Item>
      </Form>
    )
})

export default UserForm